package com.ruoyi.scan.api;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.config.vo.SUserVo;
import com.ruoyi.core.constant.Const;
import com.ruoyi.core.constant.Url;
import com.ruoyi.core.domain.bo.UserBo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import com.ruoyi.scan.domain.bo.ApplyBo;
import com.ruoyi.scan.domain.vo.ApplyVo;
import com.ruoyi.scan.service.IApplyService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 后台控制器
 */
@RestController
@RequestMapping(Url.check)
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class HController extends BaseController {
    private final IApplyService iApplyService;
    private final IUserService userService;
    private final ISysUserService iSysUserService;
    private final ISysRoleService iSysRoleService;

    /**
     * 商家申请列表
     */
    @GetMapping("listApply")
    public TableDataInfo<ApplyVo> listApply(ApplyBo bo, PageQuery pageQuery){
        // 校验是否是管理员，不是管理员就报错
        checkIsAdmin();
        //查询申请列表
        TableDataInfo<ApplyVo> info = iApplyService.queryPageList(bo, pageQuery);
        //拿到申请列表
        List<ApplyVo> rows = info.getRows();
        //
        UserBo userBo = new UserBo();
        List<UserVo> userVos = userService.queryList(userBo);

        for (ApplyVo row : rows) {
            Long uid = row.getUid();
            //SUserVo userVo = userService.getSUserVoById(uid);

            for (UserVo vo : userVos) {
                Long id = vo.getId();
                if (id.equals(uid)){
                    SUserVo sUserVo = BeanUtil.toBean(vo, SUserVo.class);
                    row. setUser(sUserVo);
                }
            }
        }
        return info;
    }

    /**
     * 商家申请详情
     */
    @GetMapping("getApply/{id}")
    private R<ApplyVo> getApply(@PathVariable Long id){
        //检查是否是管理员
        isAdmin();
        ApplyVo applyVo = iApplyService.queryById(id);
        SUserVo sUserVo = userService.getSUserVoById(applyVo.getUid());
        applyVo.setUser(sUserVo);
        return ok("查询成功",applyVo);
    }
    /**
     * 审核商家申请
     */
    @PostMapping("checkApply")
    @Transactional // 开启事务控制
    public R<Void> checkApply(@Validated(AddGroup.class) @RequestBody ApplyBo bo){
        //检查是否是管理员
        isAdmin();
        Long id = bo.getId();
        ApplyVo applyVo = iApplyService.queryById(id);

        if(ObjectUtil.isNull(applyVo)){
            return fail("审核不存在");
        }
        if (!"0".equals(applyVo.getIsCheck())){
            return fail("已审核");
        }
        Long uid = applyVo.getUid();
            UserVo userVo = userService.queryById(uid);

        String isCheck = bo.getIsCheck();



        switch (isCheck){
            //通过
            case "1":
                applyVo.setIsCheck("1");
                applyVo.setAgreeTime(new Date());
                break;
            //驳回
            case "2":
                if(StringUtils.isBlank(applyVo.getRejectItem())){
                    return  fail("请提供驳回项");
                }
                if (StringUtils.isBlank((applyVo.getRejectReason()))){
                    return fail("请提供驳回原因");
                }
                applyVo.setRejectItem(applyVo.getRejectItem());
                applyVo.setRejectReason(applyVo.getRejectReason());
                applyVo.setIsCheck("2");
                break;
           //拒绝
            case "3":
                if (StringUtils.isBlank((applyVo.getRejectReason()))){
                    return fail("请提供拒绝原因");
                }
                applyVo.setRejectReason(applyVo.getRejectReason());
                applyVo.setIsCheck("3");
                break;
            default:
                return fail("状态有误");
        }
        iApplyService.updateByBo(BeanUtil.toBean(applyVo,ApplyBo.class));
        switch (isCheck){
            case "1":
                //公众号消息通知用户，保存系统消息

                //设置用户身份
                userVo.setIsSj(Const.sj); // 设置用户身份
                userVo.setTel(applyVo.getTel());
                userService.updateByBo(BeanUtil.toBean(userVo,UserBo.class));
                // 在后台创建用户账号
                register(userVo);

                return ok("已通过");
            case "2":
                return ok("已驳回");
            case "3":
                return ok("已拒绝");
            default:
                return fail("系统错误");
        }
    }

    private void register(UserVo userVo) {
        String tel = userVo.getTel();
        // 初始化密码
        String initPassword = SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.user.initPassword");


        Long [] roleIds = new Long [] {2L};

        SysUser sysUser = new SysUser();
        sysUser.setUserName(tel); // 设置用户名
        sysUser.setNickName(userVo.getNickname());
        sysUser.setPhonenumber(tel); // 设置电话
        sysUser.setAvatar(userVo.getAvatar());
        sysUser.setPassword(BCrypt.hashpw(initPassword)); // 加密后设置密码
        sysUser.setDeptId(104L); // 设置部门id
        sysUser.setRoleId(2L); // 设置角色id
        sysUser.setRoleIds(roleIds);

        sysUser.setUserType(UserType.SYS_USER.getUserType()); // 设置用户类型为pc端

        // 校验用户名是否是唯一端
        if (UserConstants.NOT_UNIQUE.equals(iSysUserService.checkUserNameUnique(sysUser))) {
            throw new UserException("user.register.save.error", tel);
        }
        //执行注册方法
        boolean regFlag = iSysUserService.registerUser(sysUser);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }

        //用户注册完成后设置角色
        iSysUserService.insertUserAuth(sysUser.getUserId(),sysUser.getRoleIds());
    }

}
